package cmd

import (
	"fmt"
	"io/fs"
	"path/filepath"
	"strings"

	"gitee.com/bjf-fhe/apicat/config"
	"gitee.com/bjf-fhe/apicat/errors"
	"gitee.com/bjf-fhe/apicat/featuredb"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

const (
	configFileName = "apicat"
)

var NoAPIDefinition = errors.New

var rootConfig config.Config

func initializeConfig(cmd *cobra.Command) error {
	v := viper.New()

	v.SetConfigFile(filepath.FromSlash(rootConfig.Config))

	if err := v.ReadInConfig(); err != nil {
		logrus.Debugf("打开配置文件发生错误: [%T]%v\n", err, err)
		if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
			if _, ok := err.(*fs.PathError); !ok {
				return err
			}
		}
	}

	v.SetEnvPrefix("APICAT")
	v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
	v.AutomaticEnv()

	// Bind the current command's flags to viper
	bindFlags(cmd, v)

	featuredb.Init(rootConfig.DbName, rootConfig.IPHashLength)

	return nil
}

func bindFlags(cmd *cobra.Command, v *viper.Viper) {
	cmd.Flags().VisitAll(func(f *pflag.Flag) {
		//if config is not set in command-line and set in config file
		if !f.Changed && v.IsSet(f.Name) {
			val := v.Get(f.Name)
			cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val))
		}
	})
}
